package com.xxx.dict.controller;

import com.github.pagehelper.PageInfo;
import com.xxx.base.utils.R;

import com.xxx.dict.domain.Dict;
import com.xxx.dict.query.DictQuery;
import com.xxx.dict.service.IDictService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/Dict")
@Api(tags = "数据字典类接口")
public class DictController {
    @Autowired
    private IDictService dictService;

    @GetMapping
    @ApiOperation(value = "查询所有")
    public R<List<Dict>> finfAll(){
        List<Dict> list = dictService.findAll();
        return R.ok(list);
    }
    @GetMapping("/{id}")
    @ApiOperation(value = "ID查询单个")
    public R<Dict> findOne(@PathVariable Long id) {
        Dict Dict = dictService.findOne(id);
        return R.ok(Dict);
    }
    @PostMapping
    @ApiOperation(value = "分页查询")
    public PageInfo<Dict> findByPage(@RequestBody DictQuery dictQuery) {
        List<Dict> byPage = dictService.findByPage(dictQuery);
        PageInfo<Dict> pageInfo = new PageInfo<>(byPage);
        return pageInfo;
    }

    @PutMapping
    @ApiOperation(value = "增加或者修改")
    public R<Void> updateOrInsert(@RequestBody Dict dict){
        try {
            if (dict.getId()!=null){
                dictService.updateById(dict);
            }else {
                dictService.insert(dict);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return R.fail("用户名重复");
        }
        return R.ok();
    }

    @DeleteMapping("/{id}")
    @ApiOperation(value = "删除用户")
    public R<Void> delete(@PathVariable Long id){
        dictService.deleteById(id);
        return R.ok();
    }


    @PatchMapping
    @ApiOperation(value = "批量删除用户")
    public R<Void> bathDicts(@RequestBody Long[] ids) {
        try {
            dictService.bathDicts(ids);
        } catch (Exception e) {
            e.printStackTrace();
            return R.fail();
        }
        return R.ok();
    }
}
